package com.ruoyi.product.service.impl;

import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.product.domain.ProductCategory;
import com.ruoyi.product.domain.vo.*;
import com.ruoyi.product.mapper.ProductCategoryMapper;
import com.ruoyi.product.service.IProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 商品分类Service业务层处理
 *
 * @author liuhizhong
 * @date 2025-07-11
 */
@Service
public class ProductCategoryServiceImpl implements IProductCategoryService {
    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    /**
     * 查询商品分类
     *
     * @param id 商品分类主键
     * @return 商品分类
     */
    @Override
    public ProductCategory selectProductCategoryById(Long id) {
        return productCategoryMapper.selectProductCategoryById(id);
    }

    /**
     * 查询商品分类列表
     *
     * @param productCategory 商品分类
     * @return 商品分类
     */
    @Override
    public List<ProductCategory> selectProductCategoryList(ProductCategory productCategory) {
        List<ProductCategory> productCategoryList = productCategoryMapper.selectProductCategoryList(productCategory);

        // 构建树形结构
        return buildTree(productCategoryList);
    }

    /**
     * 一级分类商品列表
     *
     * @param
     */
    @Override
    public List<ProductCategoryDetail1Vo> selectProductCategoryList1Detail(Long id) {
        List<ProductCategoryDetail1Vo> mapList = productCategoryMapper.selectProductCategoryList1Detail(id);
        if (mapList == null || mapList.isEmpty()) {
            return null;
        }

        // 获取顶级分类名称
        String topCategoryName = productCategoryMapper.getTopCategoryName(id);

        // 按分类名称分组数据
        Map<String, List<ProductCategoryVo>> categoryProductMap = new LinkedHashMap<>();
        Map<Long, ProductCategoryVo> spuMap = new LinkedHashMap<>();
        Map<Long, Sku> skuMap = new LinkedHashMap<>();
        Map<Long, Activity> activityMap = new LinkedHashMap<>();
        Map<Long, Coupon> couponMap = new LinkedHashMap<>();

        for (ProductCategoryDetail1Vo item : mapList) {
            if (item.getSpuId() == null) {
                continue;
            }

            Long spuId = item.getSpuId();

            // 处理SPU信息
            ProductCategoryVo productInfo = spuMap.get(spuId);
            if (productInfo == null) {
                productInfo = new ProductCategoryVo();
                productInfo.setSpuId(spuId);
                productInfo.setSpuName(item.getSpuName());
                productInfo.setSpuTitle(item.getSpuTitle());
                productInfo.setSpuDescription(item.getSpuDescription());
                productInfo.setSkus(new ArrayList<>());
                spuMap.put(spuId, productInfo);
            }

            // 处理SKU信息
            if (item.getSkuId() != null) {
                Long skuId = item.getSkuId();
                Sku sku = skuMap.get(skuId);
                if (sku == null) {
                    sku = new Sku();
                    sku.setSkuId(item.getSkuId());
                    sku.setSpuId(item.getSpuId());
                    sku.setCode(item.getCode());
                    sku.setCategoryId(item.getCategoryId());
                    sku.setSpecData(item.getSpecData());
                    sku.setPrice(item.getPrice());
                    sku.setOriginalPrice(item.getOriginalPrice());
                    sku.setSkuName(item.getSkuName());
                    sku.setDescription(item.getDescription());
                    sku.setStock(item.getStock());
                    sku.setLowStock(item.getLowStock());
                    sku.setWeight(item.getWeight());
                    sku.setVolume(item.getVolume());
                    sku.setStatus(item.getStatus());
                    sku.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
                    sku.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));
                    sku.setCreatedAt(item.getCreatedAt());
                    sku.setUpdatedAt(item.getUpdatedAt());
                    sku.setUrl(item.getUrl());
                    sku.setUrls(new ArrayList<>());
                    sku.setCouponList(new ArrayList<>());
                    sku.setActivityList(new ArrayList<>());
                    skuMap.put(skuId, sku);
                }

                // 处理图片URL
                if (item.getUrl() != null && !item.getUrl().isEmpty() && !sku.getUrls().contains(item.getUrl())) {
                    sku.getUrls().add(item.getUrl());
                }
            }

            // 处理活动信息
            if (item.getActivityId() != null) {
                Long activityId = item.getActivityId();
                Activity activity = activityMap.get(activityId);
                if (activity == null) {
                    activity = new Activity();
                    activity.setActivityId(item.getActivityId());
                    activity.setActivityName(item.getActivityName());
                    activity.setActivityType(item.getActivityType());
                    activity.setActivityEndTime(item.getActivityEndTime());
                    activity.setActivityDescription(item.getActivityDescription());
                    activity.setActivityStatus(item.getActivityStatus());
                    activity.setActivityCreateTime(item.getActivityCreateTime());
                    activityMap.put(activityId, activity);
                }
            }

            // 处理优惠券信息
            if (item.getCouponId() != null) {
                Long couponId = item.getCouponId();
                Coupon coupon = couponMap.get(couponId);
                if (coupon == null) {
                    coupon = new Coupon();
                    coupon.setCouponId(item.getCouponId());
                    coupon.setCouponCode(item.getCouponCode());
                    coupon.setCouponType(item.getCouponType());
                    coupon.setCouponValue(item.getCouponValue());
                    coupon.setCouponMinAmount(item.getCouponMinAmount());
                    coupon.setCouponStartTime(item.getCouponStartTime());
                    coupon.setCouponEndTime(item.getCouponEndTime());
                    couponMap.put(couponId, coupon);
                }
            }
        }

        // 将SKU关联到对应的SPU，并关联活动和优惠券
        for (ProductCategoryDetail1Vo item : mapList) {
            if (item.getSkuId() != null) {
                Long skuId = item.getSkuId();
                Sku sku = skuMap.get(skuId);
                if (sku != null) {
                    // 关联活动到SKU
                    if (item.getActivityId() != null) {
                        Activity activity = activityMap.get(item.getActivityId());
                        if (activity != null && !sku.getActivityList().contains(activity)) {
                            sku.getActivityList().add(activity);
                        }
                    }
                    // 关联优惠券到SKU
                    if (item.getCouponId() != null) {
                        Coupon coupon = couponMap.get(item.getCouponId());
                        if (coupon != null && !sku.getCouponList().contains(coupon)) {
                            sku.getCouponList().add(coupon);
                        }
                    }
                }
            }
        }

        // 将SKU添加到对应的SPU
        for (Sku sku : skuMap.values()) {
            Long spuId = sku.getSpuId();
            ProductCategoryVo productInfo = spuMap.get(spuId);
            if (productInfo != null) {
                productInfo.getSkus().add(sku);
            }
        }

        // 按分类名称分组产品
        for (ProductCategoryDetail1Vo item : mapList) {
            if (item.getSpuId() != null) {
                String categoryName = item.getCategoryName();
                Long spuId = item.getSpuId();
                ProductCategoryVo productInfo = spuMap.get(spuId);

                if (productInfo != null) {
                    categoryProductMap.computeIfAbsent(categoryName, k -> new ArrayList<>()).add(productInfo);
                }
            }
        }

        // 去重每个分类下的产品
        for (Map.Entry<String, List<ProductCategoryVo>> entry : categoryProductMap.entrySet()) {
            List<ProductCategoryVo> products = entry.getValue();
            List<ProductCategoryVo> uniqueProducts = new ArrayList<>();
            Set<Long> addedSpuIds = new HashSet<>();

            for (ProductCategoryVo product : products) {
                if (!addedSpuIds.contains(product.getSpuId())) {
                    uniqueProducts.add(product);
                    addedSpuIds.add(product.getSpuId());
                }
            }
            entry.setValue(uniqueProducts);
        }

        // 构建响应对象
        ProductCategoryDetail1Vo response = new ProductCategoryDetail1Vo();
        response.setTopCategoryName(topCategoryName);
        response.setCategoryProductList(categoryProductMap);

        return Arrays.asList(response);
    }

    /**
     * 二级分类商品列表
     *
     * @param id
     */
    @Override
    public List<ProductCategoryDetail2Vo> selectProductCategoryList2Detail(Long id) {
        List<ProductCategoryDetail2Vo> mapList = productCategoryMapper.selectProductCategoryList2Detail(id);
        if (mapList == null || mapList.isEmpty()) {
            return null;
        }

        // 获取分类名称（从第一条记录中获取）
        String categoryName = mapList.get(0).getCategoryName();

        // 按SPU分组数据
        Map<Long, ProductCategoryVo> spuMap = new LinkedHashMap<>();
        Map<Long, Sku> skuMap = new LinkedHashMap<>();
        Map<Long, Activity> activityMap = new LinkedHashMap<>();
        Map<Long, Coupon> couponMap = new LinkedHashMap<>();

        for (ProductCategoryDetail2Vo item : mapList) {
            if (item.getSpuId() == null) {
                continue;
            }

            Long spuId = item.getSpuId();

            // 处理SPU信息
            ProductCategoryVo productInfo = spuMap.get(spuId);
            if (productInfo == null) {
                productInfo = new ProductCategoryVo();
                productInfo.setSpuId(spuId);
                productInfo.setSpuName(item.getSpuName());
                productInfo.setSpuTitle(item.getSpuTitle());
                productInfo.setSpuDescription(item.getSpuDescription());
                productInfo.setSkus(new ArrayList<>());
                spuMap.put(spuId, productInfo);
            }

            // 处理SKU信息
            if (item.getSkuId() != null) {
                Long skuId = item.getSkuId();
                Sku sku = skuMap.get(skuId);
                if (sku == null) {
                    sku = new Sku();
                    sku.setSkuId(item.getSkuId());
                    sku.setSpuId(item.getSpuId());
                    sku.setCode(item.getCode());
                    sku.setCategoryId(item.getCategoryId());
                    sku.setSpecData(item.getSpecData());
                    sku.setPrice(item.getPrice());
                    sku.setOriginalPrice(item.getOriginalPrice());
                    sku.setSkuName(item.getSkuName());
                    sku.setDescription(item.getDescription());
                    sku.setStock(item.getStock());
                    sku.setLowStock(item.getLowStock());
                    sku.setWeight(item.getWeight());
                    sku.setVolume(item.getVolume());
                    sku.setStatus(item.getStatus());
                    sku.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(item.getSpecNameGroupRaw()));
                    sku.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(item.getSpecValueGroupRaw()));
                    sku.setCreatedAt(item.getCreatedAt());
                    sku.setUpdatedAt(item.getUpdatedAt());
                    sku.setUrl(item.getUrl());
                    sku.setUrls(new ArrayList<>());
                    sku.setCouponList(new ArrayList<>());
                    sku.setActivityList(new ArrayList<>());
                    skuMap.put(skuId, sku);
                }

                // 处理图片URL
                if (item.getUrl() != null && !item.getUrl().isEmpty() && !sku.getUrls().contains(item.getUrl())) {
                    sku.getUrls().add(item.getUrl());
                }
            }

            // 处理活动信息
            if (item.getActivityId() != null) {
                Long activityId = item.getActivityId();
                Activity activity = activityMap.get(activityId);
                if (activity == null) {
                    activity = new Activity();
                    activity.setActivityId(item.getActivityId());
                    activity.setActivityName(item.getActivityName());
                    activity.setActivityType(item.getActivityType());
                    activity.setActivityEndTime(item.getActivityEndTime());
                    activity.setActivityDescription(item.getActivityDescription());
                    activity.setActivityStatus(item.getActivityStatus());
                    activity.setActivityCreateTime(item.getActivityCreateTime());
                    activityMap.put(activityId, activity);
                }
            }

            // 处理优惠券信息
            if (item.getCouponId() != null) {
                Long couponId = item.getCouponId();
                Coupon coupon = couponMap.get(couponId);
                if (coupon == null) {
                    coupon = new Coupon();
                    coupon.setCouponId(item.getCouponId());
                    coupon.setCouponCode(item.getCouponCode());
                    coupon.setCouponType(item.getCouponType());
                    coupon.setCouponValue(item.getCouponValue());
                    coupon.setCouponMinAmount(item.getCouponMinAmount());
                    coupon.setCouponStartTime(item.getCouponStartTime());
                    coupon.setCouponEndTime(item.getCouponEndTime());
                    couponMap.put(couponId, coupon);
                }
            }
        }



        // 将SKU关联到对应的SPU，并关联活动和优惠券
        for (ProductCategoryDetail2Vo item : mapList) {
            if (item.getSkuId() != null) {
                Long skuId = item.getSkuId();
                Sku sku = skuMap.get(skuId);
                if (sku != null) {
                    // 关联活动到SKU
                    if (item.getActivityId() != null) {
                        Activity activity = activityMap.get(item.getActivityId());
                        if (activity != null && !sku.getActivityList().contains(activity)) {
                            sku.getActivityList().add(activity);
                        }
                    }
                    // 关联优惠券到SKU
                    if (item.getCouponId() != null) {
                        Coupon coupon = couponMap.get(item.getCouponId());
                        if (coupon != null && !sku.getCouponList().contains(coupon)) {
                            sku.getCouponList().add(coupon);
                        }
                    }
                }
            }
        }

        // 将SKU添加到对应的SPU
        for (Sku sku : skuMap.values()) {
            Long spuId = sku.getSpuId();
            ProductCategoryVo productInfo = spuMap.get(spuId);
            if (productInfo != null) {
                productInfo.getSkus().add(sku);
            }
        }

        // 构建响应对象
        ProductCategoryDetail2Vo response = new ProductCategoryDetail2Vo();
        response.setCategoryName(categoryName);
        response.setProductList(new ArrayList<>(spuMap.values()));

        return Arrays.asList(response);
    }

    /**
     * 构建树形结构
     *
     * @param list 平铺的商品分类列表
     * @return 树形结构的商品分类列表
     */
    private List<ProductCategory> buildTree(List<ProductCategory> list) {
        List<ProductCategory> result = new ArrayList<>();
        Map<Long, ProductCategory> map = new HashMap<>();

        // 将所有项放入Map中，方便查找
        for (ProductCategory item : list) {
            map.put(item.getId(), item);
            // 初始化children列表
            item.setChildren(new ArrayList<SimpleProductCategory>());
        }

        // 构建树形结构
        for (ProductCategory item : list) {
            if (item.getParentId() == null || item.getParentId() == 0) {
                // 根节点
                result.add(item);
            } else {
                // 子节点，添加到父节点的children中，只保留id和name
                ProductCategory parent = map.get(item.getParentId());
                if (parent != null) {
                    @SuppressWarnings("unchecked")
                    List<SimpleProductCategory> children = (List<SimpleProductCategory>) parent.getChildren();
                    children.add(new SimpleProductCategory(item.getId(), item.getName()));
                }
            }
        }

        return result;
    }

    /**
     * 新增商品分类
     *
     * @param productCategory 商品分类
     * @return 结果
     */
    @Override
    public int insertProductCategory(ProductCategory productCategory) {
        return productCategoryMapper.insertProductCategory(productCategory);
    }

    /**
     * 修改商品分类
     *
     * @param productCategory 商品分类
     * @return 结果
     */
    @Override
    public int updateProductCategory(ProductCategory productCategory) {
        return productCategoryMapper.updateProductCategory(productCategory);
    }

    /**
     * 批量删除商品分类
     *
     * @param ids 需要删除的商品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoryByIds(Long[] ids) {
        return productCategoryMapper.deleteProductCategoryByIds(ids);
    }

    /**
     * 删除商品分类信息
     *
     * @param id 商品分类主键
     * @return 结果
     */
    @Override
    public int deleteProductCategoryById(Long id) {
        return productCategoryMapper.deleteProductCategoryById(id);
    }

    /**
     * 简化的商品分类类，只包含id和name
     */
    public static class SimpleProductCategory {
        private Long id;
        private String name;

        public SimpleProductCategory(Long id, String name) {
            this.id = id;
            this.name = name;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
